
class UserCenterModal {
    constructor() {
        this.modal = document.getElementById('userCenterModal');
        this.initEventListeners();
    }

    initEventListeners() {
        document.querySelector('[data-action="user-center"]').addEventListener('click', () => {
            this.show();
        });

        // Tab切换事件
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                this.switchTab(tab.dataset.tab);
            });
        });

        // 头像上传事件
        document.getElementById('avatarInput').addEventListener('change', (e) => {
            this.handleAvatarUpload(e);
        });

        // 关闭按钮
        this.modal.querySelector('.close-btn').addEventListener('click', () => this.hide());

        // 遮罩层关闭
        this.modal.addEventListener('click', (e) => {
            if (e.target === this.modal) this.hide();
        });

        // 表单提交
        document.getElementById('userInfoForm')?.addEventListener('submit', (e) => this.handleUserInfo(e));
        document.getElementById('passwordForm')?.addEventListener('submit', (e) => this.handlePassword(e));
    }

    // 新增Tab切换方法
    switchTab(tabName) {
        // 切换标签样式
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.toggle('active', tab.dataset.tab === tabName);
        });

        // 切换内容面板
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.toggle('active', panel.dataset.tab === tabName);
        });
    }

    // 修改后的头像上传方法
    async handleAvatarUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        // 验证文件类型
        const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            Alert.show('仅支持JPG/PNG/GIF格式', 'warning');
            return;
        }

        try {
            const formData = new FormData();
            formData.append('avatarfile', file);

            // 显示上传状态
            const avatarPreview = document.getElementById('avatarPreview');
            avatarPreview.classList.add('uploading');

            // 调用上传接口
            const response = await fetch(API.USER_CENTER.UPDATE_AVATAR, {
                method: 'POST',
                body: formData
                // 不要设置Content-Type头，浏览器会自动生成正确的multipart/form-data
            });

            const result = await response.json();
            if (result.code !== 0) {
                throw new Error(result.msg || '上传失败');
            }

            // 更新预览
            const reader = new FileReader();
            reader.onload = (e) => {
                avatarPreview.src = e.target.result;
                avatarPreview.classList.remove('uploading');
            };
            reader.readAsDataURL(file);

            // 刷新用户信息
            userDropdown.loadUserInfo();
            Alert.show('头像更新成功', 'success');
        } catch (error) {
            Alert.show(`上传失败: ${error.message}`, 'error');
            document.getElementById('avatarInput').value = '';
        }
    }

    async show() {
        console.log('show 显示用户中心');
        try {
            const data = await fetchData(API.USER_CENTER.USER_INFO);
            this.fillFormData(data);
            this.modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        } catch (e) {
            Alert.show('加载用户信息失败', 'error');
        }
    }

    hide() {
        this.modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    fillFormData(data) {
        const form = document.getElementById('userInfoForm');
        form.elements.userName.value = data.userName || '';
        form.elements.phonenumber.value = data.phonenumber || '';
        form.elements.email.value = data.email || '';
        form.elements.sex.value = data.sex || '0';
        document.getElementById('avatarPreview').src = data.avatar || '/images/avatars/default-logo.png';
    }

    async handleUserInfo(e) {
        e.preventDefault();
        const formData = {
            userName: e.target.userName.value,
            phonenumber: e.target.phonenumber.value,
            email: e.target.email.value,
            sex: e.target.sex.value
        };

        try {
            await fetchResponse(API.USER_CENTER.UPDATE_USER, formData);
            Alert.show('信息更新成功', 'success');
            this.hide();
            userDropdown.loadUserInfo();
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    async handlePassword(e) {
        e.preventDefault();
        const formData = {
            oldPassword: e.target.oldPassword.value,
            newPassword: e.target.newPassword.value,
            confirmPassword: e.target.confirmPassword.value
        };

        if (formData.newPassword !== formData.confirmPassword) {
            Alert.show('两次输入密码不一致', 'warning');
            return;
        }

        try {
            await fetchResponse(API.USER_CENTER.RESET_PASSWORD, {
                oldPassword: formData.oldPassword,
                newPassword: formData.newPassword
            });
            Alert.show('密码修改成功', 'success');
            this.hide();
            e.target.reset();
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }
}

// 初始化
const userDropdown = new UserDropdown();
const userCenterModal = new UserCenterModal();